using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

public enum StripType { Alpha, Numeric, AlphaNumeric, Printable }
/*****************************************************************************
 * Class: HTMLHelper 
 * by:    Phil Allison
 * Description: Intented to help format and remove errors in data conversion
 * and/or screen displays. 
 * 
 * List of Functions:
 * =================
 * NewlineToBR - change Newline characters to HTML breaks
 * Date    - Return a string from a DateTime object.
 * Integer - Convert input to integer value.
 * Decimal - Convert input to decimal value.
 * Money   - Return given value as a money formatted string. (e.g. $1.50)
 * MaxLen  - Return a string not exceeding the given length. 
 * MoneyPM - Return money formatted with a plus or minus sign. (e.g. +$1.50)
 * Address - take an address ovbject and format it for HTML display.
 * PhoneNumber - Formats input to (999)999-9999 format.
 * Percentage  - Formats input into whole number with percent symbol (e.g. 50%)
 * EmailClean  - Removes given email adderss from a string of email addresses.
 * isNumeric   - Determines if a string is numeric. 
*****************************************************************************/
namespace sgsBase
{
	public class HTMLHelper
	{
		public static string Msg = "";
		/// <summary>
		/// Return HTML string with breaks in place of newlines
		/// </summary>
		/// <param name="input"></param>
		/// <returns>formatted string</returns>
		/// <remarks>Phil Allison</remarks>
		public static string NewlineToBR(string input)
		{
			string ret = input.Replace("\n", "<br>");

			return ret;
		}

		public static string Timestamp()
		{
			return DateTime.Now.ToString();
		}
        /// <summary>
        /// Convert DateTime to Date Only string
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        /// <remarks>Phil Allison</remarks>
		/// Brian P. Love - Added input for type string.
		/// Phil - Added input type object
        public static string Date(DateTime dt)
        {
			return Date(dt, "&nbsp;");
        }
		public static string Date(DateTime dt, string def)
		{
			string ret = dt.ToShortDateString();
			if (ret == "1/1/0001") //basic check for null date
				ret = def;

			return ret;
		}
		public static string Date(string dt)
		{
			return Date(dt, "&nbsp;");
		}
        public static string Date(string dt, string def)
        {
            string ret = "";
            try 
	        {
				dt = dt.Replace("EST", "").Replace("EDT", "");
                ret = DateTime.Parse(dt).ToShortDateString();
	        }
	        catch (Exception)
	        {
                ret = def;
	        }
            if (ret == "1/1/0001") //basic check for null date
                ret = def;

            return ret;
        }
		public static string Date(object dt)
		{
			string ret = "&nbsp;";
			if (dt == null)
				return ret;

			return Date(dt.ToString());
		}

		public static string DateISO(DateTime dt)
		{
			return DateISO(dt, "-");
		}
		public static string DateISO(DateTime dt, string sep)
		{
			string ret = "";
			ret = dt.Year.ToString() + sep + dt.Month.ToString("00") + sep + dt.Day.ToString("00");
			return ret;
		}
		public static string DateISO(DateTime dt, bool incTime, string sep)
		{
			string ret = "";
			ret = dt.Year.ToString() + sep + dt.Month.ToString("00") + sep + dt.Day.ToString("00");
			if (incTime)
				ret += " " + dt.Hour.ToString("00") + ":" + dt.Minute.ToString("00") + ":" + dt.Second.ToString("00");
			return ret;
		}

		public static string ShortDateTime(object dt)
		{
			DateTime dtt = CASTHelper.Date(dt);

			string ret = dtt.Month.ToString() + "/" + dtt.Day.ToString() + " " + dtt.Hour.ToString().PadLeft(2, '0') + ":" + dtt.Minute.ToString().PadLeft(2, '0');

			if (ret == "1/1 00:00")
				return "";

			return ret;
		}
		public static string DateAndTime(object dt)
		{
			DateTime dtt = CASTHelper.Date(dt);

			string ret = Date(dtt, "") + " " + dtt.Hour.ToString().PadLeft(2, '0') + ":" + dtt.Minute.ToString().PadLeft(2,'0');

			if (ret == " 00:00")
				return "";

			return ret;
		}

		public static string Time(object dt)
		{
			if (CASTHelper.isNumeric(dt))
			{
				int val = CASTHelper.Integer(dt);

				if (val > 100)
				{
					string str = (val / 100).ToString() + ":" + (val - (val/100*100)).ToString().PadLeft(2,'0');
					dt = (object)str;
				}
			}
			DateTime ddt = CASTHelper.Date(dt);

			return ddt.ToShortTimeString();
		}

		public static string Time(decimal dt)
		{
			int inp = CASTHelper.Integer(dt);

			if (inp > 100)
			{
				string str = (inp / 100).ToString() + ":" + (inp - (inp / 100 * 100)).ToString().PadLeft(2, '0');
				return Time(str);
			}

			if (inp != dt)
			{
				return inp.ToString() + ":30";
			}

			return inp.ToString() + ":00";
		}
		/// <summary>
		/// Convert Value to Decimal
		/// </summary>
		/// <param name="inp"></param>
		/// <returns>Decimal value. 0 if input could not be converted</returns>
		/// <remarks>Phil Allison</remarks>
		public static decimal Decimal(int inp)
		{
			return Convert.ToDecimal(inp);
		}
		public static decimal Decimal(string inp)
		{
			decimal ret = 0;
			if (inp == "")
				return ret;

			inp = inp.Replace("$", "").Replace(",", "").Replace("(","-").Replace(")","").Trim();
			try
			{
				ret = Convert.ToDecimal(inp);
			}
			catch
			{
			}
			return ret;
		}
		public static decimal Decimal(object inp)
		{
			decimal ret = 0;
			if (inp == null)
				return ret;

			try
			{
				ret = Convert.ToDecimal(inp);
			}
			catch
			{
			}
			return ret;
		}

		/// <summary>
		/// Returns a dollar formatted value. 
		/// </summary>
		/// <param name="inp">Input value</param>
		/// <param name="ZeroAsBlank">If true, when 0, return empty string</param>
		/// <returns></returns>
		/// <modification>Added check for parens and replaced them with leading negative (-) sign.</modification>
		public static string Money(int inp)
		{
			return Money(inp, false);
		}
		public static string Money(int inp, bool ZeroAsBlank)
		{
			decimal inp2 = (decimal)inp;
			return Money(inp2, ZeroAsBlank);
		}
		public static string Money(decimal inp)
		{
			return Money(inp, false);
		}
		public static string Money(decimal inp, bool ZeroAsBlank)
		{
            if (inp == 0 && ZeroAsBlank)
                return "";

            return inp.ToString("C");
        }
		public static string Money(long inp)
		{
			return Money(inp, false);
		}
		public static string Money(string inp)
		{
			return Money(inp, false);
		}
        public static string Money(object inp, bool ZeroAsBlank)
        {
            return Money(inp.ToString(), ZeroAsBlank);
        }
        public static string Money(string inp, bool ZeroAsBlank)
        {
			decimal dc = CASTHelper.Decimal(inp);
            return Money(dc, ZeroAsBlank);
        }
        public static string Money(object inp, string StringAsBlank)
        {
            return Money(inp.ToString(), StringAsBlank);
        }
        public static string Money(decimal inp, string StringAsBlank)
        {
            if (inp == 0)
                return StringAsBlank;

            return Money(inp);
        }
        public static string Money(string inp, string StringAsBlank)
        {
			decimal dc = CASTHelper.Decimal(inp);

            if (dc == 0)
                return StringAsBlank;

            return Money(dc);
        }
        public static string Money(object inp)
        {
            return Money(inp.ToString(), false);
        }

		public static string MoneyWhole(object inp)
		{
			string mon = Money(inp);

			return mon.Replace(".00", "");
		}

		public static string Number(object inp, int DecimalPlaces)
		{
			inp = inp.ToString().Replace("$", "").Replace(",", "");
			decimal dc = CASTHelper.Decimal(inp);
			return dc.ToString("N" + DecimalPlaces);
		}

		public static string Number(object inp)
		{
			return Number(inp, 0);
		}

		public static string YesNo(object inp)
		{
			string ino = inp.ToString();

			if (ino == "1" || ino.ToLower() == "yes" || ino.ToLower() == "true")
				return "Yes";

			return "No";
		}
		/// <summary>
		/// Return a Maximum number of characters from the string.
		/// </summary>
		/// <param name="inp"></param>
		/// <param name="len"></param>
		/// <returns>String of up to 'len' characters.</returns>
		/// <remarks>Phil Allison</remarks>
		public static string MaxLen(object inp, int len, bool includeElipses)
		{
			return MaxLen(inp.ToString(), len, includeElipses);
		}
		public static string MaxLen(string inp, int len)
		{
			return MaxLen(inp.ToString(), len, false);
		}
		public static string MaxLen(string inp, int len, bool includeElipses)
		{
			if (inp.Length < len)
				return inp;
			Msg = "Truncated to " + len.ToString() + " characters.";
			if (includeElipses)
				return inp.Substring(0, len) + "...";
			return inp.Substring(0, len);
		}

		/// <summary>
		/// Returns money with a leading +/- sign
		/// </summary>
		/// <param name="inp"></param>
		/// <returns></returns>
		public static string MoneyPM(string inp)
		{
			return MoneyPM(Decimal(inp));
		}
		public static string MoneyPM(decimal inp)
		{
			string outp = inp.ToString("C");
			if (inp > 0)
				outp = outp.Replace("$", "+$");
			else
			{
				outp = outp.Replace("$", "-$");
				outp = outp.Replace("(", "").Replace(")", "");
			}
			return outp;
		}
		public static string Address(string street, string city, string state, string zip)
		{
			string ret = street.Trim() + "<br>";

			ret += city.Trim() + ", " + state.Trim() + " " + zip.Trim();

			return ret;
		}
		//public static string Address(DtoUsrAddress inpAddress, bool inclLocName)
		//{
		//    string ret = "";

		//    if (inclLocName && inpAddress.LocName.Trim() != "")
		//        ret += inpAddress.LocName + "<br>";
		//    if (inpAddress.Address1.Trim() != "")
		//        ret += inpAddress.Address1 + "<br>";
		//    if (inpAddress.Address2.Trim() != "")
		//        ret += inpAddress.Address2 + "<br>";
		//    if (inpAddress.Address3.Trim() != "")
		//        ret += inpAddress.Address3 + "<br>";

		//    ret += inpAddress.City.Trim() + ", " + inpAddress.State.Trim() + " " + inpAddress.Zipcode.Trim();

		//    return ret;
		//}
		//public static string Address(DtoUsrAddress inpAddress)
		//{
		//    return Address(inpAddress, false);
		//}

        /// <summary>
        /// Formats the telephone number. Can handle phone numbers with and without area codes.
        /// </summary>
        /// <param name="pPhoneNumber">The phone number as string.</param>
        /// <remarks>
        /// Added by Brian P. Love on 09/17/2009 at 11:22 AM.
        /// 20090917 1138 - BPL - Updated to check for non numeric digits.
		/// 20091014 0000 - PLA - Added handling of x imbedded in input. All text past and including the 'x' is now stripped out.
        /// </remarks>
        public static string PhoneNumber(string pPhoneNumber)
        {
            string ret = "";
			//PLA20091014 - before stripping non-digits, check for an extension preceeded by an 'x', strip it off
			if (pPhoneNumber.Contains("x"))
				pPhoneNumber = pPhoneNumber.Substring(0, pPhoneNumber.IndexOf("x"));

            for (int i = 0; i < pPhoneNumber.Length; i++)
                if (Char.IsDigit(pPhoneNumber, i))
                    ret += pPhoneNumber[i];
            ret = ret.Replace(".", "");

            if ((ret.Length < 12) && (ret.Length > 6))
            {
                if (ret.Length == 7)
                    ret = string.Format("{0}-{1}", ret.Substring(0, 3), ret.Substring(3));
                else if (ret.Length == 10)
                    ret = string.Format("({0}) {1}-{2}", ret.Substring(0, 3), ret.Substring(3, 3), ret.Substring(6));
                else if (ret.Length == 11)
                    ret = string.Format("{0} ({1}) {2}-{3}", ret.Substring(0, 1), ret.Substring(1, 3), ret.Substring(4, 3), ret.Substring(7));
                else
                    ret = pPhoneNumber;
            }
            else
            {
                ret = pPhoneNumber;
            }
            return ret;
        }

        
        /// <summary>
        /// Formats the telephone number. Can handle phone numbers with and without area codes.
        /// </summary>
        /// <param name="pPhoneNumber">The phone number as integer.</param>
        /// <remarks>
        /// Added by Brian P. Love on 09/17/2009 at 11:17 AM.
        /// </remarks>
        public static string PhoneNumber(Int64 pPhoneNumber)
        {
            return PhoneNumber(pPhoneNumber.ToString());
        }

		public static string PhoneExt(string PhoneNumber)
		{
			if (!PhoneNumber.Contains("x"))
				return "";

			return PhoneNumber.Substring(PhoneNumber.IndexOf("x")+1);
		}

        /// <summary>
        /// Formats a decimal number as a percentage. Input should be in fractional form (i.e. .705 will return 70.5%
        /// </summary>
        /// <param name="value">The decimal value to process.</param>
        /// <param name="NumDecimalPlaces">The number of decimal places to return.</param>
        /// <param name="ReturnEmptyStringIfNull">If the percentage is zero, return empty string (true) or 0% (false).</param>
        /// <param name="UseDecimalPlacesOnlyIfBelowZero">Only apply the NumDecimalPlaces if the percentage is less than zero but greater than -1.</param>
        /// <remarks>
        /// Added by Brian P. Love on 09/23/2009 at 03:53 PM.
        /// </remarks>
        public static string Percentage(decimal value, int NumDecimalPlaces, bool ReturnEmptyStringIfZero, bool UseDecimalPlacesOnlyIfBelowZero)
        {
            Decimal percent = 0;    
            string retval = string.Empty;
            String strplaces = new String('0', NumDecimalPlaces);    
            
            if(value == 0)    
            {        
                percent = 0;    
            }    
            else    
            {
                percent = value * 100;
                if (NumDecimalPlaces > 0)        
                {
                    if (UseDecimalPlacesOnlyIfBelowZero)
                    {
                        if ((percent < 1) && (percent > -1))
                            strplaces = "." + strplaces;
                    }
                    else
                    {
                        strplaces = "." + strplaces;
                    }
                }    
            }        
            retval = percent.ToString("#" + strplaces);
            while (retval.StartsWith("0"))
                retval = retval.Substring(1);
            if ((retval == "") && (ReturnEmptyStringIfZero))
                return "";
            else
                return (retval == "") ? "0%" : retval + "%";
        
        }
		public static string Percentage(object val)
		{
			return Percentage(CASTHelper.Decimal(val), 2, true, false);
		}
		public static string Percentage(object val, int NumDecimalPlaces)
		{
			return Percentage(CASTHelper.Decimal(val), NumDecimalPlaces, true, false);
		}

        public static string Percentage(int value, int NumDecimalPlaces, bool ReturnEmptyStringIfZero, bool UseDecimalPlacesOnlyIfBelowZero)
        {
            decimal d = ((decimal)value / 100);
            return Percentage(d, NumDecimalPlaces, ReturnEmptyStringIfZero, UseDecimalPlacesOnlyIfBelowZero);
        }


		/// <summary>
		/// remove any reference to given email address to remove.
		/// </summary>
		/// <param name="inp"></param>
		/// <param name="toRemove">optional. sales@hawleyusa.com if omitted</param>
		/// <returns></returns>
 		public static string EmailClean(string inp)
		{
			return EmailClean(inp, "sales@hawleyusa.com");
		}
		public static string EmailClean(string inp, string toRemove)
		{
			inp = inp.ToLower().Replace(toRemove, "");
			char[] ra = { ' ', ',' };
			inp = inp.Trim(ra);
			return inp;
		}

		public static string Strip(string inp, StripType StripTo)
		{
			string ret = "";

			foreach (Char ch in inp)
			{
				if (StripTo == StripType.Alpha || StripTo == StripType.AlphaNumeric)
					if (Char.IsLetter(ch))
						ret += ch;

				if (StripTo == StripType.Numeric || StripTo == StripType.AlphaNumeric)
					if (Char.IsNumber(ch))
						ret += ch;

				if (StripTo == StripType.Printable)
					if (!Char.IsSymbol(ch))
						ret += ch;
			}

			return ret;
		}
		public static string Strip(object inp, StripType StripTo)
		{
			return Strip(inp.ToString(), StripTo);
		}

		public static string MaskedCC(object inp)
		{
			return MaskedCC(inp, 'X');
		}
		public static string MaskedCC(object inp, char pad)
		{

			string card = inp.ToString().Replace("X", "");
			
			card = card.PadLeft(16, pad);

			return card;
		}
		public static string OrdernoRelno(object inp)
		{
			string ret = inp.ToString();

			if (ret.Length == 9)
				ret = ret.Insert(6, "-");
			else
				ret += "-000";
			return ret;
		}
	}
}
